# services/common_service.py
from fastapi import UploadFile
from config import settings
import os
import uuid
from datetime import datetime
from pathlib import Path
from .ocr_service import OCRService

# 文件存储目录
STORAGE_DIR = settings.FILE_STORAGE_DIR if hasattr(settings, 'FILE_STORAGE_DIR') else "uploads"
Path(STORAGE_DIR).mkdir(parents=True, exist_ok=True)

def get_ocr_service():
    """创建OCRService实例的依赖函数"""
    return OCRService(
        chat_api_key=settings.CHAT_API_KEY,
        retriever_api_key=settings.RETRIEVER_API_KEY
    )

def save_uploaded_file(file: UploadFile) -> str:
    """保存上传文件并返回存储路径"""
    file_ext = os.path.splitext(file.filename)[1]
    unique_id = uuid.uuid4().hex
    timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
    saved_filename = f"{unique_id}_{timestamp}{file_ext}"
    
    save_path = os.path.join(STORAGE_DIR, saved_filename)
    
    with open(save_path, "wb") as f:
        f.write(file.file.read())
    
    return save_path